<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;

class IndexController extends Controller
{
    //添加
    public function add(Request $request){
        if ($request->isMethod('POST')){
            $file = $request->file('source');
            //var_dump($file);exit;
            //判断文件是否上传成功
            if ($file->isValid()){
                //原文件名
                $originalName = $file->getClientOriginalName();
                //扩展名
                $ext = $file->getClientOriginalExtension();
                //MimeType
                $type = $file->getClientMimeType();
                //临时绝对路径
                $realPath = $file->getRealPath();
                $filename = uniqid().'.'.$ext;
                $bool = Storage::disk('uploads')->put($filename,file_get_contents($realPath));
                //判断是否上传成功
                if($bool){
                    //图片上传成功  处理数据
                    //图片路径
                    $insert['source']='uploads/'.date('Ymd').'/'.$filename;
                    $insert['sort']=$request['sort'];
                    $insert['link']=$request['link'];
                    DB::table('mall_ad')->insert($insert);
                    return redirect('lists');
                    //dd($insert);
                }else{
                    echo 'fail';
                }
            }
        }else{
            return view('index');
        }
    }

    //列表页
    public function lists(){
        $data=DB::table('mall_ad')->where('is_delete',0)->paginate(10);
        //dd($data);
        return view('list',compact('data'));
    }

    public function edit(Request $request){
        if($request->link){
            $file = $request->file('source');
            if ($file && $file->isValid()){
                //原文件名
                $originalName = $file->getClientOriginalName();
                //扩展名
                $ext = $file->getClientOriginalExtension();
                //MimeType
                $type = $file->getClientMimeType();
                //临时绝对路径
                $realPath = $file->getRealPath();
                $filename = uniqid().'.'.$ext;
                $bool = Storage::disk('uploads')->put($filename,file_get_contents($realPath));
                //判断是否上传成功
                if($bool){
                    //图片上传成功  处理数据
                    //图片路径
                    $insert['source']='uploads/'.date('Ymd').'/'.$filename;
                }else{
                    echo 'fail';
                }
            }
            $insert['sort']=$request->sort;
            $insert['link']=$request->link;
            DB::table('mall_ad')->where('id',$request->id)->update($insert);
            return redirect('lists');
        }else{
            $data=DB::table('mall_ad')->find($request->id);
            return view('edit',compact('data'));
        }
    }

}
